import _ from 'lodash';
import { Request, Response, NextFunction } from 'express';
import { getNewMovie, createNewMovie, deleteNewMovie, getIdNewMovie, updateNewMovie } from './newMovie.service';
import { getVideoUrlWai } from '../videoPlay/videoPlay.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let pageNo = request.query.pageNo
  let pageSize = request.query.pageSize
  let status = 0;

  const data = await getNewMovie(parseInt(`${pageNo}`, 10), parseInt(`${pageSize}`, 10), status);

  response.send(data);
}

/**
 * 获取内容(按 ID 查找)
 */
export const newMovieDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getIdNewMovie(parseInt(postId, 10));

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 获取电影播放地址
 */
export const newMovieUrl = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { url } = request.body;

  try {
    const data = await getVideoUrlWai(url);

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let commentModel = request.body;
  let releaseTime = Math.floor(new Date().getTime())
  commentModel.releaseTime = releaseTime;
  
  // 创建内容
  try {
    if(!commentModel.id) {
      const data = await createNewMovie(commentModel);
      response.send(data);
    } else {
      const data = await updateNewMovie(commentModel, commentModel.id);
      response.send(data);
    }
    
  } catch (error) {
    next(error);
  }
}


/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.body;

  // 删除内容
  try {
    const data = await deleteNewMovie(parseInt(postId, 10));

    response.send(data);
  } catch (error) {
    next(error);
  }
};


